<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2023/3/17
 * Time: 15:22
 */

namespace App\Rep;


use App\Exceptions\ApiException;
use App\Models\ModelFields;
use App\Models\Models;
use App\Models\Order;
use App\Models\OrderChild;
use App\Models\Product;
use App\Models\ProductCenter;
use Illuminate\Support\Facades\DB;

class OrderChildRep
{

    /**获取生产订单列表**/
    public function getOrderChildListRep($params){
        $list = Order::Schedule($params)->where('is_replenishment',2)
            ->with(['color'=>function($q){
                return $q->select('id','color');
            },'product'=>function($q){
                return $q->select('id','product_name')->with(['job_type'=>function($q){
                    $q->select('product_id','job_type_id','product_job_type.sort as sort')->orderBy('sort','asc');
                }]);
            },'customer'=>function($q){
                return $q->select('id','customer_name','customer_address');
            },'modelNumber'=>function($q){
                return $q->select('id','model_number','file_id')->with(['file']);
            },'orderChild'=>function($q){
                return $q->with(['job_type'=>function($q){
                    $q->select('id','job_type','sort')->orderBy('sort','asc');
                },'employee'])->orderBy('sort','asc');
            },'specification'=>function($q){
                return $q->select('id','specification');
            },'accountExecutive'=>function($q){
                return $q->select('id','company_name','phone');
            }])
            ->orderBy('id','desc')->paginate($params['per_page']??10)->toArray();
        $data = $list['data'];
        if($data){
            foreach($data as $k=>$v){
                $product_id = $v['product_id'];
                $modelid = Product::where('id',$product_id)->value('modelid');
                $tablename = Models::where('modelid',$modelid)->value('tablename');
                $model_field = ModelFields::where('modelid',$modelid)->get();

                if($model_field){
                    foreach($model_field as $kk=>$vv){
                        if(in_array($vv->formtype,['input','textarea','inputnumber'])){
                            $data[$k]['models_field'][$vv->field] = DB::table($tablename)->where('order_id',$v['id'])->value($vv['field']);
                        }else{
                            if(!empty($vv->option_list)){
                                $option_list = explode("\n",$vv->option_list);
                                //p($option_list);
                                $option_arr = [];
                                foreach($option_list as $key=>$val){
                                    $option = explode("|",rtrim($val));
                                    //p($option);
                                    $option_arr[$option[1]] = $option[0];
                                }
                                $field_key = DB::table($tablename)->where('order_id',$v['id'])->value($vv['field']);
                                //$data[$k]['models_field'][$vv->field] = $option_arr[$field_key]??'';
                                $data[$k]['models_field'][$vv->field] = $field_key;
                                //$data[$k]['models_field'][$vv->field] = ['value'=>$option_arr[$field_key]??'','key'=>$field_key];
                            }else{
                                $data[$k]['models_field'][$vv->field] = DB::table($tablename)->where('order_id',$v['id'])->value($vv['field']);
                            }


                        }
                    }
                }

            }
        }
        $list['data'] = $data;
        return (object)$list;
    }

    /**指派订单**/
    public function assignOrderChildRep($params){
        if(empty($params['employee_user_id'])){
            throw new ApiException(20001,'未选中指派的员工');
        }
        $child_order_id = $params['child_order_id'];//子订单ID
        $orderChild = OrderChild::where('id',$child_order_id)->first();
        $orderChild->operator_user_id = $params['user_id'];//操作人
        $orderChild->employee_user_id = $params['employee_user_id'];//指派员工ID
        $orderChild->draw_time = date("Y-m-d H:i:s",time());//订单领取
        $orderChild->appoint_time = date("Y-m-d H:i:s",time());//指派时间
        $orderChild->is_appoint = 1;//指派
        $orderChild->status = 2;
        $orderChild->save();
        $orderRep = new OrderRep();
        $orderRep->setOrderProductionStatus($orderChild->order_id,1);//生产中
        return $orderChild;
    }

    /**
     * 取消指派
     */
    public function cancelAssignOrderChildRep($child_order_id){
        $orderChild = OrderChild::find($child_order_id);
        $orderChild->employee_user_id = null;
        $orderChild->draw_time = null;//订单领取
        $orderChild->appoint_time = null;//指派时间
        $orderChild->is_appoint = 2;//指派
        $orderChild->status = 3;
        $orderChild->save();
        return $orderChild;
    }


    /**外包订单**/
    public function epibolyOrderChildRep($params){
        //p($params);
        $child_order_id = $params['child_order_id'];//子订单ID
        $orderChild = OrderChild::where('id',$child_order_id)->first();
        //$orderChild->operator_user_id = $params['user_id'];//操作人
        $orderChild->epiboly_time = date("Y-m-d H:i:s",time());//订单外包时间
        $orderChild->is_epiboly = 1;
        //$orderChild->is_appoint = 2;
        $orderChild->status = 2;
        $orderChild->save();
        $orderRep = new OrderRep();
        $orderRep->setOrderProductionStatus($orderChild->order_id,1);//生产中
        return $orderChild;
    }

    /**
     * 根据订单id获取子订单列表
     * @param $params
     */
    public function getOrderChildListByOrderIdRep($params){
        $order = Order::where('id',$params['order_id'])
            ->with(['color','product','customer','modelNumber','orderChild'=>function($q){
                return $q->with(['job_type','employee','image1'=>function($q){
                    return $q->select('id','file_name','file_url');
                },'image2'=>function($q){
                    return $q->select('id','file_name','file_url');
                },'image3'=>function($q){
                    return $q->select('id','file_name','file_url');
                },'image4'=>function($q){
                    return $q->select('id','file_name','file_url');
                }]);
            }])
            ->first()->toArray();
        return $order['order_child'];
    }

    /**
     * 设置子订单状态为【完成】
     * @param $params
     */
    public function setOrderChildStatusRep($params){
        DB::beginTransaction();
        try{
            $child_order_id = $params['child_order_id'];//子订单ID
            $orderChild = OrderChild::where('id',$child_order_id)->first();
            $orderChild->operator_user_id = $params['user_id'];//操作人
            if($orderChild->is_epiboly == 1){
                //已外包
                $orderChild->status = 1;
                $orderChild->submit_time = date("Y-m-d H:i:s",time());//提交时间
            }else{
                if(empty($params['employee_user_id'])){
                    return ['code'=>1019,'msg'=>'尚未指派员工','data'=>[]];
                }
                $orderChild->employee_user_id = $params['employee_user_id'];//指派员工ID
                $orderChild->appoint_time = date("Y-m-d H:i:s",time());//订单领取/指派时间
                $orderChild->is_appoint = 1;
                //$orderChild->is_epiboly = 2;
                $orderChild->status = 1;
                $orderChild->draw_time = date("Y-m-d H:i:s",time());//领取时间
                $orderChild->submit_time = date("Y-m-d H:i:s",time());//提交时间
            }
            $orderChild->save();
            $orderRep = new OrderRep();
            $orderRep->setOrderProductionStatus($orderChild->order_id,1);//生产中
            $orderRep->selectOrderChildStatus($orderChild->order_id);//加入半成品库
            DB::commit();
            return ['code'=>0,'msg'=>'success','data'=>$orderChild];
        }catch(\Exception $exception){
            DB::rollBack();
            return ['code'=>2001,'msg'=>$exception->getMessage(),'data'=>[]];
        }

    }

    /**
     * 自动添加子订单
     * @param $product_id
     * @param $order_id
     */
    public function autoCreateOrderChild($product_id,$order_id,$model_number_id,$specification_id){
        $productRep = new ProductRep();
        $job_type_list = $productRep->getProductJobTypeListByProductId($product_id);
        $jobTypeRep = new JobTypeRep();
        foreach($job_type_list as $k=>$v){
            $center = ProductCenter::where('product_id',$product_id)
                ->where('model_number_id',$model_number_id)
                ->where('specification_id',$specification_id)
                ->where('job_type_id',$v['id'])
                ->first();
            $where = ['order_id'=>$order_id, 'job_type_id'=>$v['id']];
            $sort = $jobTypeRep->getProductJobTypeSort($product_id,$v['id']);
            OrderChild::updateOrCreate($where,['order_id'=>$order_id, 'job_type_id'=>$v['id'],'sort'=>$sort,'price'=>$center->price??0]);
        }
    }


}
